package com.fy.oa.zc.crm;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;

import com.fy.oa.zc.domain.FySummaryView;
import com.fy.oa.zc.exception.FyOAException;
import com.fy.oa.zc.manager.AFyOA_FormEventManager;
import com.fy.oa.zc.manager.FyOA_FormEventManager;
import com.fy.oa.zc.rest.FyOARestValuesBean;
import com.fy.oa.zc.soap.client.FyOA_SOAPClient;

public class FyOA2CRM_ReturnSales_ManagerImpl extends AFyOA_FormEventManager implements FyOA_FormEventManager {
	//private String soapServicePath;
	private String soapServicePath="http://10.111.0.162:7777";

	private Map<String, String> marketType;
	private Map<String, String> productType;

	public Map<String, String> getMarketType() {
		return marketType;
	}

	public void setMarketType(Map<String, String> marketType) {
		this.marketType = marketType;
	}

	public Map<String, String> getProductType() {
		return productType;
	}

	public void setProductType(Map<String, String> productType) {
		this.productType = productType;
	}

	public void setSoapServicePath(String soapServicePath) {
		this.soapServicePath = soapServicePath;
	}

	public String toString() {
		return "退货";
	}

	private String getNowTime() {
		java.util.Date date = Calendar.getInstance().getTime();
		SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
		return sdf.format(date);
	}

	private String createSendXML(FyOARestValuesBean valuesBean) {
		Map<String, String> mainValues = valuesBean.getValues();
		Map<String, List<String>> repeatValues = valuesBean.getRepeatValues();
		StringBuilder sb = new StringBuilder();
		sb.append(SENDXMLTEMPLATE_START);
		String nowTime = getNowTime();
		// Timestamp ts = new
		// Timestamp(Calendar.getInstance().getTimeInMillis());
		String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
		String month = String.valueOf(Calendar.getInstance().get(Calendar.MONTH) + 1);
		for (int i = 0, size = repeatValues.get("明细表_本厂编号").size(); i < size; i++) {
			sb.append("<fy:FyReturns>");
			sb.append("<fy:AccountCode>").append(repeatValues.get("明细表_客户编码").get(i)).append("</fy:AccountCode>");
			sb.append("<fy:AccountName>").append(repeatValues.get("明细表_客户名称").get(i)).append("</fy:AccountName>");
			sb.append("<fy:AuditDate>").append(nowTime).append("</fy:AuditDate>");
			sb.append("<fy:CauseAnalysis>").append(repeatValues.get("明细表_原因分析").get(i)).append("</fy:CauseAnalysis>");
			sb.append("<fy:Code>").append(repeatValues.get("明细表_本厂编号").get(i)).append("</fy:Code>");
			sb.append("<fy:DefectName>").append(repeatValues.get("明细表_复检缺陷").get(i)).append("</fy:DefectName>");
			sb.append("<fy:EntrepotStorage>").append(repeatValues.get("明细表_是否中转库").get(i).equals("0") ? "Y" : "N")
					.append("</fy:EntrepotStorage>");
			sb.append("<fy:MarketType>").append(marketType.get(repeatValues.get("明细表_产品类别").get(i)))
					.append("</fy:MarketType>");
			sb.append("<fy:Month>").append(month).append("</fy:Month>");
			sb.append("<fy:OANumber>").append(mainValues.get("单据编号")).append("</fy:OANumber>");
			sb.append("<fy:OrgName>").append(repeatValues.get("明细表_子公司").get(i)).append("</fy:OrgName>");
			sb.append("<fy:ProductName>").append(repeatValues.get("明细表_产品名称型号").get(i)).append("</fy:ProductName>");
			sb.append("<fy:ProductType>").append(productType.get(repeatValues.get("明细表_产品类型").get(i)))
					.append("</fy:ProductType>");
			sb.append("<fy:ReturnsQuantity>").append(repeatValues.get("明细表_退货数量").get(i))
					.append("</fy:ReturnsQuantity>");
			sb.append("<fy:SecondDefect>").append(repeatValues.get("明细表_二类缺陷").get(i)).append("</fy:SecondDefect>");
			sb.append("<fy:SerialNumber>").append(repeatValues.get("明细表_序号").get(i)).append("</fy:SerialNumber>");
			sb.append("<fy:StorageName>").append(repeatValues.get("明细表_中转库名称").get(i)).append("</fy:StorageName>");
			sb.append("<fy:Year>").append(year).append("</fy:Year>");
			sb.append("</fy:FyReturns>");
		}
		sb.append(SENDXMLTEMPLATE_END);
		return sb.toString();
	}

	private void resultParse(String xml) {
		try {
			Document doc = DocumentHelper.parseText(xml);
			doc.getRootElement().addNamespace("siebelf", "http://www.siebel.com/ws/fault");
			doc.getRootElement().addNamespace("ns", "http://siebel.com/CustomUI");
			List<?> list = doc.selectNodes("//ns:Error_spcMsg");
			if (list.size() == 1) {
				Element node = (Element) list.get(0);
				String msg = node.getText();
				if (msg != null && !"".equals(msg)) {
					throw new FyOAException("退货写入CRM失败，错误提示为：" + msg);
				}
			} else if (list.size() == 0) {
				list = doc.selectNodes("//siebelf:errormsg");
				if (list.size() == 1) {
					throw new FyOAException("退货写入CRM失败，错误提示为：" + ((Element) list.get(0)).getText());
				}
				throw new FyOAException("退货写入CRM失败，未知的错误！");
			} else {
				throw new FyOAException("退货接口返回XML数据异常，出现多个ErrorMessage");
			}
		} catch (DocumentException e) {
			throw new FyOAException("解析新客户授信接口返回XML数据发生异常", e);
		}
	}

	@Override
	public String dealFinishEvent(FySummaryView view) {
		FyOARestValuesBean valuesBean = getValuesBean(view.getSummaryid());
		String result = fyOA_SOAPClient.post(createSendXML(valuesBean),
				soapServicePath + "/eai_anon_chs/start.swe?SWEExtSource=SecureWebService&SWEExtCmd=Execute",
				"\"document/http://siebel.com/CustomUI:FYOAReturnLogicServiceOAReturnProcess\"");
		resultParse(result);
		return view.toString();
	}

	public void setFyOA_SOAPClient(FyOA_SOAPClient fyOA_SOAPClient) {
		this.fyOA_SOAPClient = fyOA_SOAPClient;
	}

	private FyOA_SOAPClient fyOA_SOAPClient;

	private static final String SENDXMLTEMPLATE_START = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:cus=\"http://siebel.com/CustomUI\" xmlns:fy=\"http://www.siebel.com/xml/FY%20Returns\"><soapenv:Header>"
			+ "<wsse:Security xmlns:wsse=\"http://schemas.xmlsoap.org/ws/2002/07/secext\">"
			+ "<wsse:UsernameToken xmlns:wsu=\"http://schemas.xmlsoap.org/ws/2002/07/utility\">"
			+ "<wsse:Username>GUESTERM</wsse:Username>"
			+ "<wsse:Password Type=\"wsse:PasswordText\">GUESTERM</wsse:Password>" + "</wsse:UsernameToken>"
			+ "</wsse:Security>" + "</soapenv:Header>" + "<soapenv:Body>"
			+ "<cus:FYOAReturnLogicServiceOAReturnProcess_Input>" + "<fy:ListOfFyReturns>";
	private static final String SENDXMLTEMPLATE_END = "</fy:ListOfFyReturns>"
			+ "</cus:FYOAReturnLogicServiceOAReturnProcess_Input>" + "</soapenv:Body>" + "</soapenv:Envelope>";
}
